#include "DXMeshResource.h"
#include <DXUT.h>
#include "Trace.h"

DXMeshResource::DXMeshResource(void): m_Mesh(NULL) {}
DXMeshResource::~DXMeshResource(void) {
	Unload();
}

bool DXMeshResource::Load(std::wstring filePath) {
	MeshResource::Load(filePath);

	//LPD3DXBUFFER materialBuffer;
	IDirect3DDevice9* device = DXUTGetD3D9Device();

	// Load the mesh from the specified file
	DWORD options = D3DXMESH_WRITEONLY;
	
	if(!m_Static)  
		options |= D3DXMESH_DYNAMIC;

	HRESULT result = D3DXLoadMeshFromX(filePath.c_str(), options, 
								 device, NULL, 
								 NULL, NULL, &m_SubsetCount, 
								 &m_Mesh );

	if(FAILED(result)) {
		m_Mesh = NULL;
		return false;
	}

	m_Mesh->GetIndexBuffer(&m_IndexBuffer);
	m_Mesh->GetVertexBuffer(&m_VertexBuffer);

	D3DINDEXBUFFER_DESC indexDesc;
	D3DVERTEXBUFFER_DESC vertexDesc;
	m_IndexBuffer->GetDesc(&indexDesc);
	m_VertexBuffer->GetDesc(&vertexDesc);

	m_Size = indexDesc.Size + vertexDesc.Size;

	//materialBuffer->Release();
	return true;
}

void DXMeshResource::Unload() {
	MeshResource::Unload();
	
	if(GetRefCount() > 0 || IsEmpty()) return;

	m_Mesh->Release();
	m_Size = 0;
}

bool DXMeshResource::Reload() {
	return Load(m_FilePath);
}

void DXMeshResource::RenderSubset(unsigned int subsetId) {
	
	Touch();

	if(IsEmpty()) {
		if(!Reload()) {
			TRACEW("Couldn't reload resource while rendering");
			return;
		}
	}

	m_Mesh->DrawSubset(subsetId);
}
